﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;

namespace PC_Client
{
    public partial class Main : Form
    {
        private readonly Unit _unit = new Unit();
        private readonly string _name = string.Empty;
        private readonly Socket _clientSocket = null;
        private List<string> _onlineUserList { get; set; }

        public Main(string name, Socket socket)
        {
            InitializeComponent();
            this._name = name;
            this._clientSocket = socket;
        }

        public void AssOnlineUser(int onlineUserNum, List<string> onlineUserList)
        {
            this.label1.Text = string.Empty;
            this.label1.Text = string.Format("在线用户（{0}）,点用户发私聊", onlineUserNum);

            _onlineUserList = onlineUserList;

            if (onlineUserList != null)
            {
                this.lvOnlineUser.Clear();
                foreach (var onlineUserItem in onlineUserList)
                {
                    this.lvOnlineUser.Items.Add(new ListViewItem { Text = onlineUserItem });
                }
            }
        }

        public void AssReceiveMsg(string msg)
        {
            this.txtReceiveMsg.AppendText(msg);
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            MessagePackage mp = new MessagePackage { ConnectType = (int)ConnectType.GroupMsg, Msg = _name + "说：" + this.txtSendMsg.Text + "\n" };
            _unit.MsgSend = Encoding.UTF8.GetBytes(JsonSerializer<MessagePackage>.GetObjectToJson(mp));

            _clientSocket.Send(_unit.MsgSend);
            this.txtSendMsg.Text = string.Empty;
        }

        private void txtSendMsg_KeyDown(object sender, KeyEventArgs e)
        {
            if (!e.Alt || e.KeyValue != 83) return;
            e.Handled = true;
            this.btnSend_Click(this, null);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Common.CloseSocket(_clientSocket, _name);
            this.Hide();
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Common.CloseSocket(_clientSocket, _name);
            this.Hide();
        }

        private void lvOnlineUser_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            MessagePackage mp = new MessagePackage { ConnectType = (int)ConnectType.LaunchWhisper, Msg = e.ItemIndex.ToString() };
            _unit.MsgSend = Encoding.UTF8.GetBytes(JsonSerializer<MessagePackage>.GetObjectToJson(mp));

            _clientSocket.Send(_unit.MsgSend);
        }
    }
}
